<template>
  <div class="main-home-layout">
    <div class="menu-container">
      <el-row
        :gutter="20"
        v-for="(itemMenu, itemIndex) in ownMenus"
        :key="itemIndex"
      >
        <template v-for="item in itemMenu" :key="item.sort">
          <el-col :span="item.span" @click="gotoPage(item)">
            <span class="bg-container">{{ item.title }}</span>
          </el-col>
        </template>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import { menus, type Menus } from './config'

import { checkAuth } from '@/utils'
import { ElMessage } from 'element-plus'

import { useStore } from '@/store'
const { useAppStore } = useStore()
const appStore = useAppStore()

const router = useRouter()

// 表示一行显示几个
const col = ref(4)

onMounted(() => {})

const ownMenus = computed(() => {
  let arr: any[] = []
  if (Array.isArray(menus) && menus.length) {
    arr = menus.reduce((acc: any[], curr, index) => {
      let _curr = {
        ...curr,
        span: 24 / col.value
      }
      if (index % col.value === 0) acc.push([])
      acc[Math.floor(index / col.value)].push(_curr)
      return acc
    }, [])
  }
  return arr
})

const gotoPage = (item: Menus) => {
  if (!item.route) return
  if (!checkAuth(item.route))
    ElMessage({
      type: 'error',
      message: '您暂无权限'
    })
  appStore.changeMainName(item.route, item.title).then((name: any) => {
    router.push({
      name
    })
  })
}
</script>

<style scoped lang="scss">
.main-home-layout {
  width: 100%;
  height: 100%;
  position: relative;

  .menu-container {
    width: 88%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .el-row {
      margin-bottom: 20px;

      .el-col {
        min-height: 20vh;

        .bg-container {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
          background-color: pink;
        }

        &:hover {
          cursor: pointer;
        }
      }

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>
